package com.amigo.online.provider.merchant.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.amigo.online.common.core.response.Response;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.param.RedisKey;
import com.amigo.online.common.param.common.KeyValueModel;
import com.amigo.online.common.param.result.adv.ProvinceAndCity;
import com.amigo.online.common.param.result.merchant.MerchantDetailInfo;
import com.amigo.online.common.param.result.merchant.MerchantHomeInfo;
import com.amigo.online.common.param.result.merchant.MerchantStatusInfo;
import com.amigo.online.provider.merchant.common.GlobalController;
import com.amigo.online.provider.merchant.common.RwRedisService;
import com.amigo.online.provider.merchant.exception.MerchantException;
import com.amigo.online.provider.merchant.mapper.CategoryMapper;
import com.amigo.online.provider.merchant.mapper.MerchantEnvironmentMapper;
import com.amigo.online.provider.merchant.mapper.MerchantManagerMapper;
import com.amigo.online.provider.merchant.mapper.MerchantMapper;
import com.amigo.online.provider.merchant.model.entity.Merchant;
import com.amigo.online.provider.merchant.service.AreaFeignService;
import com.amigo.online.provider.merchant.service.MerchantStatusService;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * <code>MerchantStatusImpl.java</code>
 * <p>
 *
 * </p>
 * <p>
 *
 * @author LuChen
 * @version 1.0
 * @company Amigo
 * @time 2018年12月24日 上午10:38:27
 * @lastUpdate 无
 * </p>
 */
@Service
@Transactional()
public class MerchantStatusImpl implements MerchantStatusService {

    @Autowired
    public MerchantManagerMapper merchantManagerMapper;

    @Autowired
    public MerchantMapper merchantMapper;

    @Autowired
    public RwRedisService redisService;

    @Autowired
    public MerchantEnvironmentMapper merchantEnvironmentMapper;

    @Autowired
    private AreaFeignService areaFeignService;

    @Autowired
    private CategoryMapper categoryMapper;

    @SuppressWarnings("unchecked")
    @Override
    public Integer getMerchantStatus() {
        Long userId = GlobalController.getNowUser().getId();
        String merchant_status_key = RedisKey.MERCHANT_STATUS_KEY + userId;
        Integer status = (Integer) redisService.opsForValueRead().get(merchant_status_key);
        if (status == null) {
            status = getMerchantStatusInfo(userId);
        }
        redisService.opsForValue().set(merchant_status_key, status);
        return status;
    }

    /**
     * @param info
     * @param userId
     * @param language
     * @return
     */
    private Integer getMerchantStatusInfo(Long userId) {
        Integer status = null;
        /** -------判断是否是店长和管理员 状态给予------- **/
        Merchant merchant = new Merchant();
        merchant.setUserId(userId);
        merchant = merchantMapper.selectApplyMerchant(merchant);// 返回申请的店铺信息 如果用户没有申请 则返回null
        Integer manager = merchantManagerMapper.checkUserIsManager(userId);// 返回用户的管理员信息 如果用户是某些的管理员 则返回数量
        if (merchant != null && manager != null && manager > 0) {
            throw new MerchantException(StatusCode.MERCHANT_EXCEPTION);
        }
        /** -------逻辑判断------- **/
        if (merchant == null && (manager == null || manager == 0)) {
            status = 0;// 新用户
        }
        if (merchant != null) { // 该用户是店长
            switch (merchant.getStatus()) {
                case 0:
                    status = 1;// 店铺申请失败
                    break;
                case 1:
                    status = 2;// 店铺申请中
                    break;
                case 2:
                    status = 3;// 店铺已拥有
                    break;
            }
        }
        if (manager != null && manager > 0) { // 该用户是管理员
            status = 4;
        }
        return status;
    }

    public MerchantStatusInfo getMerchantInfoByStatus(String language, Integer status) {
        Long userId = GlobalController.getNowUser().getId();
        // 构造返回信息
        MerchantStatusInfo info = new MerchantStatusInfo();
        MerchantHomeInfo merchantHomeInfo = null;
        MerchantDetailInfo detailInfo = new MerchantDetailInfo();
        List<MerchantHomeInfo> list = null;
        ProvinceAndCity provinceAndCity = null;
        switch (status) {
            case 0:// 新用户
                break;
            case 1:// 店铺申请失败
                merchantHomeInfo = merchantMapper.getMerchantHomeByUserId(userId, language, 0);
                if (null == merchantHomeInfo) {
                    throw new MerchantException(StatusCode.MERCHANT_EXCEPTION);
                }
                provinceAndCity = getProvinceAndCity(language, merchantHomeInfo.getStoreAreaId());
                if (provinceAndCity != null) {
                    merchantHomeInfo.setCity(provinceAndCity.getCity());
                    merchantHomeInfo.setProvince(provinceAndCity.getProvince());
                } else {
                    merchantHomeInfo.setCity("");
                    merchantHomeInfo.setProvince("");
                }
                info.setMerchantHomeInfo(merchantHomeInfo);
                break;
            case 2:// 店铺申请中
                merchantHomeInfo = merchantMapper.getMerchantHomeByUserId(userId, language, 1);
                if (null == merchantHomeInfo) {
                    throw new MerchantException(StatusCode.MERCHANT_EXCEPTION);
                }
                provinceAndCity = getProvinceAndCity(language, merchantHomeInfo.getStoreAreaId());
                if (provinceAndCity != null) {
                    merchantHomeInfo.setCity(provinceAndCity.getCity());
                    merchantHomeInfo.setProvince(provinceAndCity.getProvince());
                } else {
                    merchantHomeInfo.setCity("");
                    merchantHomeInfo.setProvince("");
                }
                info.setMerchantHomeInfo(merchantHomeInfo);
                break;
            case 3:// 该用户是店长
                merchantHomeInfo = merchantMapper.getMerchantHomeByUserId(userId, language, 2);
                if (null == merchantHomeInfo) {
                    throw new MerchantException(StatusCode.MERCHANT_EXCEPTION);
                }
                provinceAndCity = getProvinceAndCity(language, merchantHomeInfo.getStoreAreaId());
                if (provinceAndCity != null) {
                    merchantHomeInfo.setCity(provinceAndCity.getCity());
                    merchantHomeInfo.setProvince(provinceAndCity.getProvince());
                } else {
                    merchantHomeInfo.setCity("");
                    merchantHomeInfo.setProvince("");
                }
                List<Integer> countMerchant = merchantMapper.getCountsByMerchantId(merchantHomeInfo.getId());
                List<KeyValueModel<Long, String>> categoryList = categoryMapper.findLabelCategoryListByLabelId(
                        merchantHomeInfo.getCategoryId() == null ? 0 : merchantHomeInfo.getCategoryId().intValue(),
                        language);
                merchantHomeInfo.setCategory(categoryList);
                detailInfo.setMerchantInfo(merchantHomeInfo);
                detailInfo.setCountConcern(countMerchant.get(0));
                detailInfo.setCountGoods(countMerchant.get(1));
                detailInfo.setCountComment(countMerchant.get(2));
                info.setMerchantDetailInfo(detailInfo);
                break;
            case 4:// 该用户是管理员
                list = merchantMapper.getMerchantInfoList(userId);
                info.setList(list);
                break;
        }
        info.setStatus(status);
        return info;
    }

    private ProvinceAndCity getProvinceAndCity(String language, Long areaId) {
        ResponseEntity<Response> rs = areaFeignService.getProvinceAndCityByCityId(areaId,
                language == null ? "name_pt" : language);
        ObjectMapper mapper = new ObjectMapper();
        ProvinceAndCity provinceAndCity = mapper.convertValue(rs.getBody().getData(), ProvinceAndCity.class);
        return provinceAndCity;
    }

}
